package class28;

import java.util.ArrayList;
import java.util.List;

/**
 * @author zhangchaoliang
 * create 2022
 */
public class ErYaun {

    public static class Yuan {
        public int first;
        public int second;

        public Yuan(int a, int b) {
            first = a;
            second = b;
        }
    }

    public static List<Yuan> erYuan(int[] arr, int aim) {
        if (arr == null || arr.length == 0) {
            return null;
        }
        int n = arr.length;
        List<Yuan> res = new ArrayList<>();
        int L = 0;
        int R = n - 1;
        while (L < R) {
            if (arr[L] + arr[R] < aim) {
                L++;
            } else if ((arr[L] + arr[R] > aim)) {
                R--;
            } else {
                if (L == 0 || arr[L] != arr[L - 1]) {
                    res.add(new Yuan(arr[L++], arr[R]));
                } else {
                    L++;
                }
            }
        }
        return res;
    }


    public static class SanYuan {
        public int first;
        public int second;
        public int third;

        public SanYuan(int a, int b, int c) {
            first = a;
            second = b;
            third = c;
        }
    }

    public static List<SanYuan> sanYuan(int[] arr, int aim) {
        if (arr == null || arr.length == 0) {
            return null;
        }
        int n = arr.length;
        List<SanYuan> res = new ArrayList<>();
        for (int i = 0; i < n; i++) {
            int L = i + 1;
            int R = n - 1;
            int temp = aim - arr[i];
            while (L < R) {
                if (arr[L] + arr[R] < temp) {
                    L++;
                } else if (arr[L] + arr[R] > temp) {
                    R--;
                } else {
                    if (L == 0 || arr[L] != arr[L - 1]) {
                        res.add(new SanYuan(arr[i], arr[L++], arr[R]));
                    } else {
                        L++;
                    }
                }
            }
        }
        return res;
    }
}
